import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/customer'
import type { CustomerTrace } from '@/types/customer'
import { formatDateTime } from '@/utils/format'

// 查询表单
const queryForm = reactive({
  page: 1,
  limit: 10,
  keywords: '',
  admin_id: '',
})

// 跟进记录列表
const traceList = ref<CustomerTrace[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)

// 选中的跟进记录
const selectedTraces = ref<CustomerTrace[]>([])

// 客户选项
const customerOptions = ref<Array<{ id: number; name: string }>>([])
// 客户远程搜索相关（仅用于表单中）
const customerLoading = ref<boolean>(false)
const customerSearchKeyword = ref<string>('')

// 管理员选项
const adminOptions = ref<Array<{ id: number; name: string }>>([])

// 详情抽屉
const detailDrawerVisible = ref<boolean>(false)
const currentTrace = ref<CustomerTrace>({} as CustomerTrace)

// 新增/编辑抽屉
const drawerVisible = ref<boolean>(false)
const traceOperationMode = ref<'add' | 'edit'>('add')
const traceForm = reactive({
  id: 0,
  cid: '' as unknown as number, // 类型断言为数字，但让表单初始值为空字符串
  content: '',
  next_time: '' as unknown as number, // 类型断言为数字，但让表单初始值为空字符串
})

// 表单验证规则
const traceRules = {
  cid: [{ required: true, message: '请选择客户', trigger: 'change' }],
  content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
}

// 表单引用
const traceFormRef = ref<any>(null)
const queryFormRef = ref<any>(null)

// 加载客户选项 - 使用远程搜索时不再需要提前加载所有客户
const loadCustomerOptions = async () => {
  // 保留函数体但不再使用
  console.log('使用远程搜索加载客户数据')
}

// 加载管理员选项
const loadAdminOptions = async () => {
  try {
    console.log('开始加载管理员选项...')
    const response = await customerApi.getAdminList()
    if (response && response.code === 0) {
      // 处理不同的响应格式
      let adminData: any[] = []
      if (Array.isArray(response.data)) {
        console.log('直接使用响应数组数据')
        adminData = response.data
      } else if (
        response.data &&
        typeof response.data === 'object' &&
        'list' in response.data &&
        Array.isArray((response.data as any).list)
      ) {
        console.log('使用响应对象中的list数组')
        adminData = (response.data as any).list
      }

      // 如果数据为空，添加一些默认选项用于测试和备用
      if (adminData.length === 0) {
        console.log('管理员数据为空，添加默认选项')
        adminData = [
          { id: 1, name: '管理员1' },
          { id: 2, name: '管理员2' },
          { id: 3, name: '管理员3' },
        ]
      }

      console.log('原始数据:', adminData)
      adminOptions.value = adminData.map((item: any) => ({
        id: item.id,
        name: item.name || item.username || item.nickname || `管理员${item.id}`,
      }))
      console.log('管理员选项加载完成:', adminOptions.value)
    } else {
      console.error('加载管理员选项失败:', response?.msg)
      // 失败时添加默认选项
      adminOptions.value = [
        { id: 1, name: '管理员1' },
        { id: 2, name: '管理员2' },
        { id: 3, name: '管理员3' },
      ]
      console.log('加载失败，使用默认选项:', adminOptions.value)
    }
  } catch (error) {
    console.error('加载管理员选项失败:', error)
    // 异常时添加默认选项
    adminOptions.value = [
      { id: 1, name: '管理员1' },
      { id: 2, name: '管理员2' },
      { id: 3, name: '管理员3' },
    ]
    console.log('发生异常，使用默认选项:', adminOptions.value)
  }
}

// 处理查询
const handleSearch = async () => {
  loading.value = true
  try {
    const params: any = {
      page: queryForm.page,
      limit: queryForm.limit,
    }

    if (queryForm.keywords) {
      params.keywords = queryForm.keywords
    }

    if (queryForm.admin_id) {
      params.admin_id = queryForm.admin_id
    }

    const response = await customerApi.getTraceList(params)
    if (response && response.code === 0) {
      traceList.value = response.data || []
      total.value = response.count || 0

      // 确保所有必要的字段都存在，并处理时间字段
      traceList.value.forEach(item => {
        item.customer_name = item.customer_name || `客户ID: ${item.cid}`
        item.admin_name = item.admin_name || ''
        // 确保时间字段是数字类型
        item.create_time = item.create_time ? Number(item.create_time) : 0
        item.next_time = item.next_time ? Number(item.next_time) : 0
      })
    } else {
      traceList.value = []
      total.value = 0
      ElMessage.error(response?.msg || '获取跟进记录列表失败')
    }
  } catch (error) {
    traceList.value = []
    total.value = 0
    console.error('获取跟进记录列表失败:', error)
    ElMessage.error('获取跟进记录列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  queryForm.keywords = ''
  queryForm.admin_id = ''
  queryForm.page = 1
  handleSearch()
}

// 新增跟进记录
const handleAdd = () => {
  traceOperationMode.value = 'add'
  // 重置表单
  traceForm.id = 0
  traceForm.cid = 0
  traceForm.content = ''
  traceForm.next_time = 0

  drawerVisible.value = true
}

// 编辑跟进记录
const handleEdit = async (row: CustomerTrace) => {
  traceOperationMode.value = 'edit'
  // 填充表单数据
  traceForm.id = row.id
  traceForm.cid = row.cid
  traceForm.content = row.content
  // 如果next_time是秒级时间戳，转换为毫秒级用于日期选择器
  traceForm.next_time = row.next_time ? Number(row.next_time) * 1000 : 0

  // 如果有客户名称，直接添加到选项中
  if (row.customer_name && row.cid) {
    // 确保客户选项中包含当前客户
    const existingOption = customerOptions.value.find(option => option.id === row.cid)
    if (!existingOption) {
      customerOptions.value.push({
        id: row.cid,
        name: row.customer_name,
      })
    }
  }

  drawerVisible.value = true
}

// 查看跟进记录详情
const handleView = (row: CustomerTrace) => {
  currentTrace.value = { ...row }
  detailDrawerVisible.value = true
}

// 删除跟进记录
const handleDelete = (row: CustomerTrace) => {
  ElMessageBox.confirm(`确定要删除该跟进记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await customerApi.deleteCustomerTrace(row.id)
        if (response && response.code === 0) {
          ElMessage.success('删除成功')
          handleSearch()
        } else {
          ElMessage.error(response?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除跟进记录失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 批量删除跟进记录
const handleBatchDelete = () => {
  if (selectedTraces.value.length === 0) {
    ElMessage.warning('请先选择要删除的跟进记录')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的${selectedTraces.value.length}个跟进记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const ids = selectedTraces.value.map(item => item.id)
        // 这里需要根据实际API调整批量删除的实现
        const deletePromises = ids.map(id => customerApi.deleteCustomerTrace(id))
        const results = await Promise.all(deletePromises)

        // 检查所有删除操作是否都成功
        const allSuccess = results.every(result => result && result.code === 0)

        if (allSuccess) {
          ElMessage.success('批量删除成功')
          handleSearch()
        } else {
          ElMessage.error('部分删除失败')
          handleSearch()
        }
      } catch (error) {
        console.error('批量删除跟进记录失败:', error)
        ElMessage.error('批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 处理选择变化
const handleSelectionChange = (selection: CustomerTrace[]) => {
  selectedTraces.value = selection
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  queryForm.page = 1
  handleSearch()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  handleSearch()
}

// 关闭详情抽屉
const closeDetailDrawer = () => {
  detailDrawerVisible.value = false
}

// 关闭新增/编辑抽屉
const closeDrawer = () => {
  drawerVisible.value = false
  if (traceFormRef.value) {
    traceFormRef.value.resetFields()
  }
}

// 提交表单
const handleSubmit = () => {
  if (traceFormRef.value) {
    traceFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const formData = {
            ...traceForm,
            cid: typeof traceForm.cid === 'string' ? parseInt(traceForm.cid) : traceForm.cid,
            next_time: traceForm.next_time ? Math.floor(Number(traceForm.next_time) / 1000) : 0,
          }

          // 确保时间字段是整数
          if (formData.next_time) {
            formData.next_time = parseInt(formData.next_time.toString())
          }

          let response
          if (traceOperationMode.value === 'add') {
            response = await customerApi.addCustomerTrace(formData)
          } else {
            response = await customerApi.editCustomerTrace({ ...formData, id: traceForm.id })
          }

          if (response && response.code === 0) {
            ElMessage.success(traceOperationMode.value === 'add' ? '新增成功' : '编辑成功')
            drawerVisible.value = false
            handleSearch()
          } else {
            ElMessage.error(
              response?.msg || (traceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
            )
          }
        } catch (error) {
          console.error('保存跟进记录失败:', error)
          ElMessage.error(traceOperationMode.value === 'add' ? '新增失败' : '编辑失败')
        }
      }
    })
  }
}

// 远程搜索客户
const remoteSearchCustomers = async (query: string) => {
  if (query.trim() === '') {
    customerOptions.value = []
    return
  }

  customerLoading.value = true
  customerSearchKeyword.value = query

  try {
    const response = await customerApi.searchCustomers(query.trim())
    if (response && response.code === 0) {
      customerOptions.value = response.data || []
    } else {
      customerOptions.value = []
      console.error('搜索客户失败:', response?.msg)
    }
  } catch (error) {
    customerOptions.value = []
    console.error('搜索客户失败:', error)
  } finally {
    customerLoading.value = false
  }
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  queryForm,
  traceList,
  total,
  loading,
  selectedTraces,
  detailDrawerVisible,
  currentTrace,
  drawerVisible,
  traceOperationMode,
  traceForm,
  traceRules,
  customerOptions,
  adminOptions,
  customerLoading,
  traceFormRef,
  queryFormRef,

  // 方法
  handleSearch,
  handleReset,
  handleAdd,
  handleEdit,
  handleView,
  handleDelete,
  handleBatchDelete,
  handleSelectionChange,
  handleSizeChange,
  handleCurrentChange,
  closeDetailDrawer,
  closeDrawer,
  handleSubmit,
  loadCustomerOptions,
  loadAdminOptions,
  remoteSearchCustomers,
  formatDateTime,
}

// 注意：在Vue组件中使用onMounted，而不是在这里
